package cn.usian.service.Impl;

import cn.usian.common.R;
import cn.usian.dao.DishDao;
import cn.usian.entity.Dish;
import cn.usian.exception.NameException;
import cn.usian.service.DishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;

@Service
@Transactional
public class DishServiceImpl  implements DishService {
    @Resource
    private DishDao dishDao;

    @Override
    public R findPage(int page, int pageSize,String name) {
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name!=null,Dish::getName,name);
        queryWrapper.orderByAsc(Dish::getSort);
        Page<Dish> dishPage = dishDao.selectPage(pageInfo,queryWrapper);
        return R.success(dishPage);
    }

    @Override
    public void save(Dish dish) {
        if (findByName(dish.getName())!=null){
            throw new NameException(dish.getName());
        }
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dishDao.insert(dish);
    }

    @Override
    public Dish findByName(String name) {
       LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(Dish::getName,name);
       return dishDao.selectOne(queryWrapper);
    }


    @Override
    public void del(String[] split) {
        for (String s : split) {
            dishDao.deleteById(s);
        }
    }

    @Override
    public void tingy(String[] split) {
        for (String id : split) {
            dishDao.updat(id);
        }
    }

    @Override
    public void qiy(String[] split) {
        for (String id : split) {
            dishDao.upda(id);
        }
    }
}
